class UsersController < ApplicationController
  before_filter :login_required
  
  
  # render new.rhtml
  def new
    @groups = Group.find(:all)
    @heading = 'New user'
    @user = User.new
  end
  
  def set_password
    @user = User.find(params[:id])
    @heading = "Set user's password"
    return unless request.post?
    if (params[:password] == params[:password_confirmation])
      @user.password_confirmation = params[:password_confirmation]
      @user.password = params[:password]
      flash[:notice] = @user.save ?
            "Password changed" :
            "Password not changed"
	    redirect_back_or_default(users_path)
    else
      flash[:notice] = "Password mismatch" 
      @old_password = params[:old_password]
    end
  end
  
  def change_password
    @user = current_user
    return unless request.post?
    if User.authenticate(current_user.login, params[:old_password])
      if (params[:password] == params[:password_confirmation])
        current_user.password_confirmation = params[:password_confirmation]
        current_user.password = params[:password]
        flash[:notice] = current_user.save ?
              "Password changed" :
              "Password not changed"
  	    redirect_back_or_default(tickets_path)
      else
        flash[:notice] = "Password mismatch" 
        @old_password = params[:old_password]
      end
    else
      flash[:notice] = "Wrong password" 
    end
  end
  
  def index
    @users = User.find(:all, :order => :login)
  end
  
  def edit
    @user = User.find(params[:id])
    @groups = Group.find(:all)
    @heading = 'Changing user details'
  end
  
  def show
    @user = User.find(params[:id])
    @groups = Group.find(:all)
  end
  
  def destroy
     user = User.find(params[:id])
     user.destroy
     redirect_to users_url
  end
  
  def update
    @user = User.find(params[:id])
    if params[:groups]
      @user.groups = Group.find(params[:groups])
    else
      @user.groups = []
    end 
    if @user.update_attributes(params[:user])
      redirect_to users_url
    else #rescue ActiveRecord::RecordInvalid
      @groups = Group.find(:all)
      render :action => 'edit'
    end
  end

  def create
    @user = User.new(params[:user])
    @user.groups = Group.find(params[:groups]) if params[:groups]
    @user.save!
    redirect_to users_url
  rescue ActiveRecord::RecordInvalid
    @groups = Group.find(:all)
    render :action => 'new'
  end

end
